<template>
  <div class="status-echarts-wrap" v-loading="loading">
    <p v-if="info.hasAnalog == 0 || info.hasAnalog == 2" class="chat-title">状态变化</p>
    <div v-if="info.hasAnalog == 1 || info.hasAnalog == 2" :id="analogDomId"></div>
    <div v-if="info.hasAnalog == 0 || info.hasAnalog == 2"  :id="domId" :class="{'content-analog-chart': (info.hasAnalog == 0 || info.hasAnalog == 2)}"></div>
    <div v-if="noDataFlag">暂无数据</div>
  </div>
</template>
<script>
import { getAlarmFcfAnalogInfo } from '@/api/alarm'
import { getFacsHisStatus } from '@/api/fcf'
import utils from '@/utils/util'
import { setTimeout } from 'timers';

export default {
  name: "StatusEcharts",
  props: {
    info: {
      required: true
    },
    type: {
      required: true
    }
  },
  data() {
    return {
      domId: 'historyChart_' + this.info.id + '_' + this.type + 'waper',
      analogDomId: 'historyAnalogChart_' + this.info.id + '_' + this.type + 'waper',
      noDataFlag: false,
      loading: false
    }
  },
  created() {
    let that = this

    if (that.info.hasAnalog == 1) {
      that.drawHasAnalogHistoryChart(that.info.id, that.type)
    } else if (that.info.hasAnalog == 2) {
      that.drawHasAnalogHistoryChart(that.info.id, that.type)
      that.drawNoAnalogChart(that.info.id, that.type)
    } else {
      that.drawNoAnalogChart(that.info.id, that.type)
    }
  },
  methods: {
    // 24小时/一周/一个月状态变化 有模拟量
    drawHasAnalogHistoryChart(fcfId, type) {
      var self = this;
      var yDataValue = [];
      var yData = [];
      var yMax = null;
      var hours = self.type == 1 ? 24 : (self.type == 2 ? 24*7 : 24*30)
      var params = {
        startTime: utils.ilinkTimeformat.hoursAgo(hours, 'yyyy-MM-dd hh:mm:ss'),
        fcfId: fcfId,
        num: 100
      };
      this.loading = true
      getAlarmFcfAnalogInfo(params).then(res => {
          let data = res.data
          if (data && data.length > 0) {
            self.noDataFlag = true
            //处理模拟量类型数据  设备电压不画
            if (data.length == 1 && data[0].dataTypeId == 3) {
              // 不显示
              self.noDataFlag = true
              return false
            }
            for (var i = 0; i < data.length; i++) {
              yDataValue = [];
              yData = [];
              if (data[i].dataTypeId != 3) {
                if (data[i].detail && data[i].detail.length > 0) {
                  self.noDataFlag = false
                  let dataTime = data[i].detail;
                  for (var n = 0; n < dataTime.length; n++) {
                    yDataValue.push(dataTime[n].analogValue);
                    yData.push({
                      name: dataTime[n].datetime,
                      value: [
                        utils.ilinkTimeformat.format(new Date(dataTime[n].datetime), 'yyyy-MM-dd hh:mm'),
                        dataTime[n].analogValue
                      ]
                    });
                  }
                  $('#'+self.analogDomId).append(
                    `<div class="every-type-chart-wrap" id="every-historyChart-` + data[i].dataTypeId + `" style="padding:20px 0">
                      <p class="chat-title" id="historyChart-bar-title">` + data[i].dataTypeName + `变化（` + data[i].detail[0].analogUnits + `）</p>
                      <div class="content-analog-chart" id="historyChart-bar-` + fcfId + '_' + data[i].dataTypeId + `"></div>
                    </div>`
                  )
                  //y轴最大值
                  yMax = Math.max(...yDataValue);
                  yMax = Math.max(
                    yMax,
                    data[i].thresholdMax ? data[i].thresholdMax : 0
                  );
                  self.drawEqChartEqmentMsg(
                    yDataValue,
                    yData,
                    yMax,
                    data[i].thresholdMin ? data[i].thresholdMin : 0,
                    data[i].thresholdMax ? data[i].thresholdMax : 0,
                    data[i].dataTypeName,
                    'historyChart-bar-' + fcfId + '_' + data[i].dataTypeId,
                    data[i].detail[0].analogUnits
                  )
                } 
              }
            }
          } else {
            // 暂无数据
            self.noDataFlag = true
          }
          this.loading = false
      });
    },
    //24小时/一周/一个月状态变化图表---没有模拟量
    drawNoAnalogChart (fcfId, type) {
      var self = this;
      var xData = [];
      var yData = [];
      this.loading = true
      getFacsHisStatus({
        fcfId: fcfId,
        type: type
      }).then(res => {
          let data = res.data
          let date = ''
          
          for (var i = 0; i < data.length; i++) {
            // 根据周期对X轴分类
            if(type == 1) {
              date = data[i].date.toString().slice(8, 10) + ":00";
            } else {
              date = data[i].date.toString().slice(4, 6) + '-' + data[i].date.toString().slice(6, 8);
            }
            xData.push(date);
            var y = data[i].fireTType;
            if (y == 0 || !y) {
              y = 5;
            } else if (y == 10) {
              y = 25;
            } else if (y == 20) {
              y = 20;
            } else if (y == 30) {
              y = 15;
            } else if (y == 40) {
              y = 10;
            } else {
              y = 5;
            }
            yData.push(y);
          }
          // 渲染不是模拟量---最近二十四小时状态变化
          if(!document.getElementById(self.analogDomId)) {
            self.$nextTick(() => {
              self.hoursChangeChart(xData, yData)
            })
          } else {
            self.hoursChangeChart(xData, yData)
          }
          this.loading = false
      })
    },
    //画折线图
    drawEqChartEqmentMsg (yDataValue, yAxisData, yMax, thresholdMin, thresholdMax, title, el, analogUnits) {
      var self = this
      var markLineArr = []

      if(thresholdMin) {
        markLineArr.push({
          name: '下阈值',yAxis: thresholdMin, 
        })
      }
      if(thresholdMax) {
        markLineArr.push({
          name: '上阈值',yAxis: thresholdMax
        })
      }

      var options = {
        title: {
          text: ""
        },
        grid: {
          top: "10%",
          left: "3%",
          right: "5%",
          bottom: "0",
          containLabel: true
        },
        tooltip: {
          backgroundColor: "white",
          borderColor: "gray", // 提示边框颜色
          borderRadius: 4, // 提示边框圆角，单位px，默认为4
          borderWidth: 1,
          position: function(p) {
            //其中p为当前鼠标的位置
            return [p[0] - 28, p[1] - 70];
          },
          padding: 5,
          trigger: "axis",
          formatter: function(e) {
            var data = e[0];
            return (
              `<span style='color:gray;font-size:12px;'>` +
              data.value[0] +
              `</span><br/><span style='color:red;font-size:14px;'>` +
              data.value[1] +
              analogUnits +
              `</span>`
            );
          },
          textStyle: { align: "center" },
          confine: true
        },
        xAxis: [
          {
            type: "time",
            boundaryGap: false,
            axisLine: {
              lineStyle: {
                color: "rgba(225, 225, 225, 0.3)"
              }
            },
            axisLabel: {
              show: true,
              textStyle: {
                color: "#666"
              },
              formatter: function(params) {
                return utils.ilinkTimeformat.format(new Date(params), 'yyyy-MM-dd hh:mm')
              }
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: "#f4f7f9"
              }
            }
          }
        ],
        yAxis: [
          {
            type: "value",
            max: yMax,
            splitNumber: 0.5,
            axisLine: {
              lineStyle: {
                color: "rgba(225, 225, 225, 0.3)"
              }
            },
            axisLabel: {
              show: true,
              textStyle: {
                color: "#666"
              },
              formatter: function(params) {
                return "";
              }
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: "#f4f7f9"
              }
            }
          }
        ],
        series: [
          {
            type: "line",
            areaStyle: {
              normal: {
                color: new self.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: "rgba(57, 126, 206, 0.6)" },
                  { offset: 0.5, color: "rgba(57, 126, 206, 0.4)" },
                  { offset: 1, color: "#fff" }
                ])
              }
            },
            smooth: true,
            showSymbol: false, //不展示节点
            itemStyle: {
              normal: {
                color: "rgba(55, 139, 246, 0.8)", // 会设置点和线的颜色，所以需要下面定制
                borderColor: "rgba(55, 139, 246, 0.8)" // 点边线的颜色
              }
            },
            lineStyle: {
              normal: {
                color: "rgba(55, 139, 246,0.9)" // 线条颜色
              }
            },
            markLine: {
              itemStyle:{
                normal:{
                  lineStyle:{
                    type:'dashed',color:'red'
                  },
                  label:{
                    show:true,
                    position:"middle",//'start' 线的起始点。'middle' 线的中点。'end' 线的结束点。
                    formatter:function(param){
                      return param.name+param.value
                    },
                    textStyle: {
                        fontSize: 14,
                    }
                  }
                }
              },
              //symbolSize:0,
              silent: true,
              data: markLineArr
            },
            data: yAxisData,
          }
        ]
      }
      this.$nextTick(() => {
        let dom=this.$el.querySelector('#'+el)
        if(!dom) return 
        var eqChart = this.$echarts.init(dom)
        eqChart.setOption(options)
      })
    },
    // 不是模拟量---最近二十四小时状态变化
    hoursChangeChart (xData, yData) {
      var self = this;
      //报警
      var fireColr = new self.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: "rgba(254, 102, 104, 1)" },
        { offset: 0.002, color: "rgba(254, 102, 104, 0.95)" },
        { offset: 0.03, color: "rgba(254, 102, 104, 0.15)" },
        { offset: 0.7, color: "rgba(254, 102, 104, 0.1)" },
        { offset: 0.9, color: "rgba(254, 102, 104, 0.05)" },
        { offset: 1, color: "rgba(254, 102, 104, 0.05)" }
      ]);
      //故障
      var faultColr = new self.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: "rgba(248, 183, 40, 1)" },
        { offset: 0.002, color: "rgba(248, 183, 40, 0.95)" },
        { offset: 0.03, color: "rgba(248, 183, 40, 0.15)" },
        { offset: 0.7, color: "rgba(248, 183, 40, 0.1)" },
        { offset: 0.9, color: "rgba(248, 183, 40, 0.05)" },
        { offset: 1, color: "rgba(248, 183, 40, 0.05)" }
      ]);
      //屏蔽
      var shieldColr = new self.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: "rgba(153, 153, 153, 1)" },
        { offset: 0.002, color: "rgba(153, 153, 153, 0.95)" },
        { offset: 0.03, color: "rgba(153, 153, 153, 0.15)" },
        { offset: 0.7, color: "rgba(153, 153, 153, 0.1)" },
        { offset: 0.9, color: "rgba(153, 153, 153, 0.05)" },
        { offset: 1, color: "rgba(153, 153, 153, 0.05)" }
      ]);
      //联动
      var linkColr = new self.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: "rgba(55, 139, 246, 1)" },
        { offset: 0.002, color: "rgba(55, 139, 246, 0.95)" },
        { offset: 0.03, color: "rgba(55, 139, 246, 0.15)" },
        { offset: 0.7, color: "rgba(55, 139, 246, 0.1)" },
        { offset: 0.9, color: "rgba(55, 139, 246, 0.05)" },
        { offset: 1, color: "rgba(55, 139, 246, 0.05)" }
      ]);
      //正常
      var normalColr = new self.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: "rgba(119, 190, 7, 1)" },
        { offset: 0.002, color: "rgba(119, 190, 7, 0.95)" },
        { offset: 0.03, color: "rgba(119, 190, 7, 0.15)" },
        { offset: 0.7, color: "rgba(119, 190, 7, 0.1)" },
        { offset: 0.9, color: "rgba(119, 190, 7, 0.05)" },
        { offset: 1, color: "rgba(119, 190, 7, 0.05)" }
      ]);
      let dom=this.$el.querySelector('#'+self.domId)
      if(!dom) return 
      var hourChart = self.$echarts.init(dom)
      hourChart.setOption({
        title: {
          text: ""
        },
        tooltip: {
          trigger: "axis",
          formatter: function(e) {
            if (e[0].value == 5) {
              return (
                "<div style='text-align: left;padding-left: 6px;'>" +
                e[0].name +
                "</div><div style='padding-left: 6px;'>状态：正常</div>"
              );
            } else if (e[0].value == 10) {
              return (
                "<div style='text-align: left;padding-left: 6px;'>" +
                e[0].name +
                "</div><div style='padding-left: 6px;'>状态：联动</div>"
              );
            } else if (e[0].value == 15) {
              return (
                "<div style='text-align: left;padding-left: 6px;'>" +
                e[0].name +
                "</div><div style='padding-left: 6px;'>状态：屏蔽</div>"
              );
            } else if (e[0].value == 20) {
              return (
                "<div style='text-align: left;padding-left: 6px;'>" +
                e[0].name +
                "</div><div style='padding-left: 6px;'>状态：故障</div>"
              );
            } else if (e[0].value == 25) {
              return (
                "<div style='text-align: left;padding-left: 6px;'>" +
                e[0].name +
                "</div><div style='padding-left: 6px;'>状态：报警</div>"
              );
            }
          }
        },
        grid: {
          top: "12%",
          left: "5%",
          right: "4%",
          bottom: "0",
          containLabel: true
        },
        xAxis: [
          {
            type: "category",
            data: xData,
            splitLine: {
              show: true,
              lineStyle: {
                type: "dotted",
                color: "rgba(225, 225, 225, 0.3)"
              }
            },
            axisTick: {
              show: false
            },
            axisLine: {
              lineStyle: {
                color: "rgba(225, 225, 225, 0.3)"
              }
            },
            axisLabel: {
              show: true,
              textStyle: {
                color: "#666"
              }
            }
          }
        ],
        yAxis: [
          {
            type: "value",
            interval: 5,
            max: 25,
            splitLine: {
              show: true,
              lineStyle: {
                color: "rgba(225, 225, 225, 0.3)"
              }
            },
            axisTick: {
              show: false
            },
            axisLine: {
              lineStyle: {
                color: "rgba(225, 225, 225, 0.3)"
              }
            },
            axisLabel: {
              show: true,
              textStyle: {
                color: "#666"
              },
              formatter: function(value) {
                if (value == 5) {
                  return "正常";
                } else if (value == 10) {
                  return "联动";
                } else if (value == 15) {
                  return "屏蔽";
                } else if (value == 20) {
                  return "故障";
                } else if (value == 25) {
                  return "报警";
                } else {
                  return "";
                }
              }
            }
          }
        ],
        series: [
          {
            type: "bar",
            // barWidth:"100%",
            itemStyle: {
              normal: {
                color: function(params) {
                  if (params.value == 5) {
                    return normalColr;
                  } else if (params.value == 10) {
                    return linkColr;
                  } else if (params.value == 15) {
                    return shieldColr;
                  } else if (params.value == 20) {
                    return faultColr;
                  } else if (params.value == 25) {
                    return fireColr;
                  }
                }
              }
            },
            data: yData
          }
        ]
      })
    }
  }
};
</script>
